#include "clientcore.h"

ClientCore::ClientCore(Core *parent) :
    QObject(parent), parent(parent){
    clientConfigPath = getClientConfigPath();
}

bool ClientCore::newClient(const QString configFile){
    QSettings* settings = new QSettings(clientConfigPath + configFile, QSettings::IniFormat);
    if (settings->status() != QSettings::NoError){
        // Error occured.
        settings->deleteLater();
        return false;
    }

    Client* client = new Client(parent, settings);
    QObject::connect(client, SIGNAL(onUnload(QString,QString)), this, SLOT(clientUnloaded(QString,QString)));

    if (client->getAlias().isEmpty() || client->getAlias() == "Core"){
        cout << QString("! Client [" + configFile + "] has an invalid alias. Generating a temporary one now...").toStdString() << endl;
        QString newAlias(QCryptographicHash::hash(configFile.toUtf8(), QCryptographicHash::Md5).toHex().left(8));
        client->setAlias(newAlias);
        cout << QString("! Client [" + configFile + "] now has the alias of [" + newAlias + "]").toStdString() << endl;
    }

    if (client->load()){
        clients.insert(client->getAlias(), client);
        return true;
    }
    client->unload();
    return false;
}

Client* ClientCore::getClient(const QString clientAlias){
    return clients.value(clientAlias);
}

bool ClientCore::hasClient(const QString clientAlias){
    Client* c = clients.value(clientAlias);
    return c;
}

bool ClientCore::hasClient(Client* client){
    return hasClient(client->getAlias());
}

bool ClientCore::removeClient(const QString clientAlias){
    Client* c = clients.value(clientAlias);
    if (c)
        c->~Client();
    int count = clients.remove(clientAlias);
    return (count > 0);
}

bool ClientCore::removeClient(Client* client){
    return removeClient(client->getAlias());
}

void ClientCore::sendConnectSignal(){
    foreach(Client* client, clients.values()){
        client->connect();
    }
}

void ClientCore::sendDisconnectSignal(){
    foreach(Client* client, clients.values()){
        client->disconnect();
    }
}


void ClientCore::clientUnloaded(const QString alias, const QString reason){
    cout << "[ClientCore][" + alias.toStdString() + "] has been unloaded due to [" + reason.toStdString() + "]";
    clients.remove(alias);
}



